import echarts from '@utils/echarts'
import { debounce } from 'lodash-es'
import { onBeforeUnmount, onActivated, watch, computed, unref, nextTick } from 'vue'
import { useThemeStroe, pinia } from '@stores'
import type { EChartsCoreOption } from 'echarts/core'
import {useLocalStorage} from './useLocalStorage'
const { state: memoryTheme } = useLocalStorage('theme')
const themeStore = useThemeStroe(pinia)
// 皮肤名称映射
const themeList = {
  fruit: 'fruit',
  light: 'new-light',
  dark: 'new-dark',
}
/**
 * @description echarts hooks，内部封装了单例、屏幕缩放、换肤的处理，建议使用图表时务必使用此hooks以达到最佳显示效果
 * @author jinzz
 * @param dom { Element } echart初始化节点
 * @param options { EchartsOption } echarts配置信息
 * @returns instance { EchartsInstance } echats实例
 * @example
 * 
 * import { useEcharts } from '@hooks/useChart'
 * useCharts(dom, { ...options })
 *  
 */
export function useEcharts(dom: HTMLElement, options: EChartsCoreOption) {
  if (!dom) {
    return
  }
  let instance = echarts.getInstanceByDom(dom)
  // 屏幕缩放
  const resizeHandler = debounce(() => {
    if (instance) {
      instance.resize()
    }
  }, 100)
  if (!instance) {
    instance = echarts.init(dom, themeList[unref(memoryTheme) as keyof typeof themeList] || '')
    window.addEventListener('resize', resizeHandler)
    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeHandler)
    })
    onActivated(resizeHandler)
  }

  // 换肤处理
  const themeName = computed(() => themeStore.getTheme)
  watch(
    () => themeName.value,
    (themeName) => {
      instance?.dispose()
      console.log(123, unref(themeName))
      console.log(themeList[unref(themeName) as keyof typeof themeList])
      instance = echarts.init(dom, themeList[unref(themeName) as keyof typeof themeList] || '')
      instance.setOption(unref(options))
    },
    {
      deep: true
    }
  )
  nextTick(() => {
    if (instance) {
      instance?.setOption(unref(options))
    }
  })
  return instance
}
